package com.booklove.domain.query;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.booklove.exception.PasswordEditFailedException;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 使用泛型的方法对分页查询的代码进行简化
 */
@Data
public class PageQuery {
    private Integer pageNo;
    private Integer pageSize;
    private String sortBy;
    private Boolean isAsc;

    /**
     * 设置初始化信息和默认值
     */
    PageQuery() {
        pageNo = 1;
        pageSize = 10;
    }


    public <T> Page<T> toMpPage(OrderItem... orders) {
        // 1.分页条件
        Page<T> p = Page.of(pageNo, pageSize);
        // 2.看有没有手动指定排序字段
        if (orders != null) {
            p.addOrder(orders);
        }
        return p;
    }


    public <T> Page<T> toMpPageDefaultSortByCreateTimeDesc() {
        OrderItem orderItem = new OrderItem();
        orderItem.setAsc(false);
        orderItem.setColumn("created_time");
        return toMpPage(orderItem);
    }

    public <T> Page<T> toMpPageDefaultSortByUpdateTimeDesc(OrderItem... orderItems) {
        if (orderItems == null || orderItems.length == 0) {
            OrderItem orderItem = new OrderItem();
            orderItem.setAsc(false);
            orderItem.setColumn("updated_time");
            return toMpPage(orderItem);
        }
        return toMpPage(orderItems);
    }

    public <T> Page<T> toMpPageDefaultSortByIdAsc(OrderItem... orderItems) {
        // 如果没有字段需要排序，自动添加id字段排序
        if (orderItems == null || orderItems.length == 0) {
            OrderItem orderItem = new OrderItem();
            orderItem.setAsc(true);
            orderItem.setColumn("id");
            return toMpPage(orderItem);
        }
        return toMpPage(orderItems);
    }


    /**
     * 快速获取 sortBy 和 排序isASC，然后生成OrderItem条件
     * 将所需要的规则字段转换为orderItem字段
     * 目前这种语法最多只允许一个字段进行sort
     * @return
     */
    public List<OrderItem> toMpOrderItems() {
        Map<String, Boolean> orderMap = new HashMap<>();
        // 为null或者为空的时候不进行设置
        if (!StrUtil.isBlankIfStr(getSortBy())) {
            Boolean boolValue = getIsAsc();
            if (boolValue == null) {
                boolValue = false;
            }
            orderMap.put(getSortBy(), boolValue);
        }
        // 设置规则
        List<OrderItem> orderItems = new ArrayList<>();
        orderMap.forEach((key, value) -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setColumn(key).setAsc(value);
            orderItems.add(orderItem);
        });
        return orderItems;
    }
}
